﻿/// <reference path="core/Error.js"/>
/// <reference path="FaScript.js"/>

Namespace("FaScript.Notify");

FaScript.Notify.defineClass('NotificationCenter',
    function () {
        var object = Object.create(null);

        var _notifyCenter = window.webkitNotifications;
        var _notifies = {};

        var support_permission = function () {
            if (!_notifyCenter) return false;

            switch (_notifyCenter.checkPermission()) {
                case 0:
                    return true;
                case 1:
                    _notifyCenter.requestPermission();
                    return support_permission();
                case 2:
                    return false;
            }
        };

        //----- 方法 Begin -----
        Object.defineProperty(object, 'show', {
            value: function (id, json) {
                /// <summary>显示通知</summary>
                /// <param name="id" type="String" >通知ID</param>
                /// <param name="json" type="JSON" >
                /// 通知内容
                /// { title: '标题', icon: '图标地址', content: '内容', time: 显示时间 }
                /// </param>
                var notify;

                if (support_permission()) {
                    notify = _notifyCenter.createNotification(
                        json.icon || '',
                        json.title || '',
                        json.content || ''
                    );
                    notify.replaceId = id;

                    if (json.time) {
                        setTimeout(function () {
                            object.close(id);
                        }, json.time * 1000);
                    }
                }

                _notifies[id] = notify;
                notify.show();
            }
        });
        Object.defineProperty(object, 'close', {
            value: function (id, json) {
                /// <summary>显示通知</summary>
                /// <param name="id" type="String" >通知ID</param>
                /// <param name="value" type="JSON" >通知内容</param>
                
                if (_notifies[id]) {
                    _notifies[id].close();
                    delete _notifies[id];
                }
            }
        });
        //----- 方法 End -----

        //锁定成员
        Object.seal(object);
        return object;
    });